package online.hxstart.code.concurrent.chapter07;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.TimeUnit;

/**
 * @author huxing
 * @date 2019/7/11 星期四 11:49
 * @describe
 */
public class ThreadHookTest {

  private static final String LOCK_PATH = "D:\\java\\lock\\32132";
  private static final String LOCK_FILE = ".lock";

  private static final String PERMISSION = "rw-------";

  public static void main(String[] args) throws IOException {
    //
    Runtime.getRuntime()
        .addShutdownHook(
            new Thread(
                () -> {
                  System.out.println("The program receive kill SIGNAL");
                  getLockFile().toFile().delete();
                }));
    checkRunning();

    for (; ; ) {
      try {
        TimeUnit.MILLISECONDS.sleep(1);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
  }

  private static void checkRunning() throws IOException {

    Path path = getLockFile();

    assert path != null;
    if (path.toFile().exists()) {
      throw new RuntimeException("the program already running");
    }

    //Windows 不支持
//    Set<PosixFilePermission> permissions = PosixFilePermissions.fromString(PERMISSION);
//    Files.createFile(path, PosixFilePermissions.asFileAttribute(permissions));
    Files.createFile(path);
  }

  private static Path getLockFile() {
    Path dir = Paths.get(LOCK_PATH);
    if (!dir.toFile().exists() && dir.toFile().mkdirs()) {
      System.out.println("创建目录成功");
    }
    return Paths.get(LOCK_PATH, LOCK_FILE);
  }
}
